import { fetch, post } from 'plugins/axios'
import { Dialog, QSpinnerGears } from 'quasar'

export function loadPackage ({state, commit}, payload) {
  return new Promise((resolve, reject) => {
    fetch('/publisher/get_build/', {
      project: payload
    }).then((response) => {
      commit('loadPackageSuccess', response)
      resolve()
    }).catch((error) => {
      console.log(error.response)
    })
  }).catch((error) => {
    console.log(error)
  })
}

export function loadHost ({state, commit}, payload) {
  return new Promise((resolve, reject) => {
    fetch('/publisher/get_prev_host/', {
      project: payload
    }).then((response) => {
      commit('loadHostSuccess', response)
      resolve()
    }).catch((error) => {
      console.log(error.response)
    })
  }).catch((error) => {
    console.log(error)
  })
}

export function save ({state, dispatch, commit}, payload) {
  state.fields.Project = payload
  Dialog.create({
    title: '新增发布',
    message: '确定新增发布？',
    ok: '提交',
    cancel: '再想想'
  }).then(() => {
    state.loading.show({spinner: QSpinnerGears})
    post('/publisher/',
      state.fields
    ).then((response) => {
      dispatch('listPublish/loadTable', payload, { root: true })
      commit('saveSuccess')
    }).catch((error) => {
      if (error.response.data) {
        commit('saveFail', error.response.data)
      }
    })
  }).catch(() => {
    console.log('stay')
  })
}
